package com.pro01.backend.controller;

import com.pro01.backend.pojo.Notification;
import com.pro01.backend.pojo.PageResult;
import com.pro01.backend.pojo.Result;
import com.pro01.backend.service.NotificationService;
import com.pro01.backend.utils.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/notifications")
public class NotificationController {

    @Autowired
    private NotificationService notificationService;

    /**
     * 分页查询当前用户的通知列表
     */
    @GetMapping
    public Result<PageResult<Notification>> getNotifications(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            HttpServletRequest request) {
        try {
            Long userId = TokenUtil.getUserId(request); // 获取当前登录用户
            PageResult<Notification> pageResult = notificationService.getNotifications(userId, pageNum, pageSize);
            return Result.success(pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取通知失败：" + e.getMessage());
        }
    }

    /**
     * 查询当前用户未读通知数量
     */
    @GetMapping("/unread/count")
    public Result<Integer> getUnreadNotificationCount(HttpServletRequest request) {
        try {
            Long userId = TokenUtil.getUserId(request);
            int unreadCount = notificationService.getUnreadNotificationCount(userId);
            return Result.success(unreadCount);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取未读通知数量失败：" + e.getMessage());
        }
    }

    /**
     * 标记一条通知为已读
     */
    @PutMapping("/{id}/read")
    public Result<Void> markNotificationAsRead(@PathVariable Long id,
                                               HttpServletRequest request) {
        try {
            Long userId = TokenUtil.getUserId(request); // 当前登录用户
            notificationService.markAsRead(id, userId);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("标记通知为已读失败：" + e.getMessage());
        }
    }

    /**
     * 标记当前用户所有通知为已读
     */
    @PutMapping("/read/all")
    public Result<Void> markAllNotificationsAsRead(HttpServletRequest request) {
        try {
            Long userId = TokenUtil.getUserId(request); // 当前登录用户
            notificationService.markAllAsRead(userId);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("标记所有通知为已读失败：" + e.getMessage());
        }
    }
}
